package com.gameserver.net;

import com.report.UserInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class GameServerClient implements Runnable {

    ChannelFuture f;

    public void close() {
        //System.err.println("0channel active flag:"+f.channel().isActive());
        f.channel().close();
        //System.err.println("1channel active flag:"+f.channel().isActive());
        f.channel().close().awaitUninterruptibly();
        //System.err.println("2channel active flag:"+f.channel().isActive());
    }

    UserInfo ui;

    public GameServerClient(UserInfo ui) {
        this.ui = ui;
    }

    public void connection() {
        Bootstrap b = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("decoder", new MessageDecoder());
                            ch.pipeline().addLast("handler", new GameServerClientHandler(ui));
                        }
                    });
            f = b.connect(ui.gsip, ui.gsport);
            f.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    @Override
    public void run() {
        connection();
    }
}
